import { _decorator, Component, Node, instantiate, assetManager, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UIManager')
export class UIManager extends Component {
    private uiBundle: any = null; // 缓存Bundle对象

    async openUI(uiName: string, parentNode: Node) {
        try {
            // 获取 Bundle（如果未加载则加载）
            if (!this.uiBundle) {
                this.uiBundle = await this.loadBundle('ui');
            }

            // 加载预制体
            const prefab = await this.uiBundle.load(`prefabs/${uiName}`, Prefab);
            if (!prefab) {
                console.error(`预制体 ${uiName} 不存在`);
                return null;
            }

            // 实例化并添加到父节点
            const node = instantiate(prefab);
            parentNode.addChild(node);
            return node;
        } catch (err) {
            console.error('加载UI失败:', err);
            return null;
        }
    }

    closeUI(node: Node) {
        node.destroy();
        // // 可选：释放资源
        // if (this.uiBundle) {
        //     assetManager.releaseAsset('ui');
        //     this.uiBundle = null;
        // }
    }

    private async loadBundle(bundleName: string): Promise<any> {
        try {
            // 尝试获取Bundle，如果不存在则加载
            let bundle = assetManager.getBundle(bundleName);
            if (!bundle) {
                await assetManager.loadBundle(bundleName);
                bundle = assetManager.getBundle(bundleName);
            }
            return bundle;
        } catch (err) {
            console.error(`加载Bundle ${bundleName} 失败`, err);
            return null;
        }
    }
}